package com.example.phonesearch;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class AddressDBUtils {
    public  static String queryAddress(Context context, String phone){
        //获取SQLitedatabase数据库
        String path=context.getFilesDir()+"/address.db";

        SQLiteDatabase db= SQLiteDatabase.openDatabase(path,null,SQLiteDatabase.OPEN_READONLY);
        String address="";//返回的号码归属地
        String Regex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";
        if (phone.matches(Regex)){
            Cursor cursor=db.query("info",new String[]{"city","cardtype"},"mobileprefix=?",new String[]{ phone},null,null,null);
            //获取结果集中的结果值
            //如果结果集中有数据获取数据

            if(cursor!=null&&cursor.getCount()>0){
                //获取cardtype字段对应的数据
                cursor.moveToNext();
                address=cursor.getString(1);

            }else{
                address="未知号码";
            }

        }else {
            switch (phone.length()){
                case 3:
                    address="紧急电话";
                    break;
                case 5:
                    address="运营商电话";
                    break;
                case 7:
                case 8:
                    address="本地座机";
                    break;
                case 11:
                    address="长途电话";
                    String area=phone.substring(0,3);
                    Cursor cursor=db.query("info",new String[]{"city"},"area=?",new String[]{area},null,null,null);
                    if (cursor.moveToNext()){
                        //结果集非空，找到3为区号对应的城市
                        address=cursor.getString(0);
                        cursor.close();
                    }else{
                        //没找到3为区号，截取前4
                        area=phone.substring(0,4);
                        Cursor cursor2=db.query("info",new String[]{"city"},"area=?",new String[]{area},null,null,null);
                        if(cursor2.moveToNext()){
                            address=cursor2.getString(0);
                        }else {
                            address="未知号码";
                        }
                        cursor2.close();
                    }
                    break;
                default:
                    address="未知号码";
            }
        }
        return address;
    }
}